<template>
  <div>
    <h1 class="title">我的订单</h1>
    <!-- 搜索条件 -->
    <el-config-provider>
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item>
          <el-date-picker
            v-model="formInline.date"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="订单号">
          <el-input v-model="formInline.orderCode" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="formInline.payFlag" placeholder="请选择" clearable>
            <el-option label="待支付" value="0" />
            <el-option label="已支付" value="1" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button class="custom-button" @click="onSearch">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-config-provider>

    <!-- end -->
    <!-- 订单列表 -->
    <div v-if="orderList.length == 0"><el-empty description="暂无数据" /></div>
    <div v-else>
      <custom-table :tableData="orderList" :columns="titleData">
        <template #status="{ row }">
          <!-- 自定义单元格内容 -->
          <el-tag type="primary" v-if="row.status == 1 && row.payFlag == 1"
            >已支付</el-tag
          >
          <el-tag type="danger" v-if="row.status == 1 && row.payFlag == 0">未支付</el-tag>
          <el-tag type="info" v-if="row.status == 4">已取消</el-tag>
        </template>
        <template #fordata="{ row }">
          <!-- 自定义单元格内容 -->
          <ul>
            <li v-for="item in row.itemVos" :key="item.id" class="prdstyle">
              <div class="left">
                <img :src="item.itemPic" alt="" />
                <div>
                  <h3 class="name">{{ item.itemName }}</h3>
                  <p class="tag">
                    <span>{{ item.itemAmount }}</span
                    >元
                  </p>
                </div>
              </div>
              <div class="caozuo">
                <el-button
                  @click="downdata(item)"
                  class="custom-button"
                  v-if="row.status == 1 && row.payFlag == 1"
                  >下载</el-button
                >
                <el-button
                  class="custom-button"
                  @click="payItem(item)"
                  v-if="row.status == 1 && row.payFlag == 0"
                  >支付</el-button
                >
                <el-button
                  v-if="row.status == 1 && row.payFlag == 0"
                  @click="cancelOrderfun(row)"
                  >取消</el-button
                >
                <el-tag v-if="row.status == 4" type="info">已取消</el-tag>
              </div>
            </li>
          </ul>
        </template>
      </custom-table>
      <!-- end -->
      <div style="margin-top: 50px">
        <Pagination
          class="pagination"
          :current-page="temparam.pageNum"
          :page-size="temparam.pageSize"
          :total="totalItems"
          @update:current-page="temparam.pageNum = $event"
          @update:page-size="pageSize = $event"
          @change="loadData(temparam)"
        />
      </div>
    </div>
    <canvas ref="qrCanvas"></canvas>
  </div>
  <!-- 下载机器码填写 -->
  <MyDialog @update:visible="updateDialog" :initVisible="dialogVisible" :width="400">
    <div class="closeBtn">
      <el-button @click="handleClose" circle><i class="iconfont">&#xe60e;</i></el-button>
    </div>
    <!-- 这里可以放置对话框内容 -->
    <div class="editInput">
      <el-form :model="formInline" class="demo-form-inline">
        <el-form-item label="机器码输入">
          <el-input v-model="codeForm.code" placeholder="请输入" clearable />
        </el-form-item>

        <el-form-item>
          <button
            type="button"
            class="dioa-button__root inline-flex appearance-none items-center justify-center select-none relative whitespace-nowrap align-middle transition outline-none cursor-pointer disabled:cursor-not-allowed h-14 px-10 text-lg font-medium lg:h-12 lg:px-8 text-white bg-red hover:bg-neutral-60 active:bg-black disabled:bg-neutral-40 data-loading:text-transparent data-loading:bg-neutral-40 rounded-full border-0 w-full"
            @click="onSubmitdown"
          >
            提交
          </button>
        </el-form-item>
      </el-form>
    </div>
  </MyDialog>
  <!-- 授权框 -->
  <MyDialog @update:visible="updateDialog1" :initVisible="dialogVisible1" :width="400">
    <div class="closeBtn">
      <el-button @click="handleClose1" circle><i class="iconfont">&#xe60e;</i></el-button>
    </div>
    <div class="title">请支付</div>
    <div class="imgtag"><img :src="qrCodeUrl" alt="QR Code" width="300" /></div>
  </MyDialog>
</template>

<script setup lang="ts">
import { reactive, ref, defineEmits, watch } from "vue";
import { orderListProps } from "@/common/utils/userType";
import { getPageList, downloadDetail, cancelOrder } from "@/common/userApi";
import Pagination from "@/components/Pagination.vue";
import CustomTable from "@/components/MyTable.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { saveAsPbtxt } from "@/common/common";
import MyDialog from "@/components/MyDialog.vue";
import { userorderStore } from "@/store/orderStore";
import QRCode from "qrcode";
import { useRoute } from "vue-router";
const route = useRoute();
const orderStore = userorderStore();
// 修改父组件index的值
const emit = defineEmits(["update-value"]);
emit("update-value", 0);
console.log(route.fullPath, "33");
// 以下是订单相关内容
const orderList = ref<orderListProps[] | any>([]);
const titleData = [
  { label: "订单号", prop: "orderCode", width: 120 },
  { label: "金额", prop: "orderAmount", width: 120 },
  { label: "状态", prop: "status", type: "status", width: 120 },
  { label: "商品信息", prop: "itemVos", type: "template" },
];
// 搜索
const formInline = reactive({
  orderCode: "",
  payFlag: "",
  date: "",
});
let currentPage = ref(1);
let pageSize = ref(5);
let totalItems = ref(0); // 假设总数为100
// 加载数据的逻辑
let temparam = reactive({
  pageNum: currentPage.value,
  pageSize: pageSize.value,
  // startDateTime: formInline.date[0],
  // endDateTime: formInline.date[1],
  // orderCode: formInline.orderCode,
  // payFlag: formInline.payFlag,
});
function loadData(data?: any) {
  window.scrollTo(0, 0);
  getPageList(data).then((res) => {
    // console.log(res);
    const tempTotal = res.total + "";
    // console.log(tempTotal);
    totalItems.value = parseInt(tempTotal);
    orderList.value = res.rows;
  });
}
loadData(temparam);
// 搜索按钮
const onSearch = () => {
  const newdata = { ...temparam, ...formInline };
  const { date, ...newObject } = newdata;
  let param = null;
  if (formInline.date) {
    const temp = {
      startDateTime: formInline.date[0],
      endDateTime: formInline.date[1],
    };
    param = { ...temp, ...newObject };
  } else {
    param = newObject;
  }

  // console.log(param);
  loadData(param);
};

// 打开机器ma
const dialogVisible = ref(false);
const codeForm = reactive({
  code: "",
  itemId: 0,
  priceId: 0,
});
const downdata = (item: any) => {
  // console.log(dialogVisible, "!23");
  dialogVisible.value = true;
  codeForm.code = "";
  codeForm.itemId = item.itemId;
  codeForm.priceId = item.priceId;
};
const updateDialog = (value: boolean) => {
  // console.log(dialogVisible, "!23");
  dialogVisible.value = value;
};
const handleClose = () => {
  dialogVisible.value = false;
  // isOpen.value = false;
};

// 下载素材downloadDetail
const onSubmitdown = () => {
  if (codeForm.code == "") {
    ElMessage.error("请输入机器码");
    return;
  }
  downloadDetail(codeForm.itemId, codeForm.priceId, codeForm.code).then((res) => {
    // console.log(res);
    if (res.code == 200) {
      ElMessage({
        message: "下载成功",
        type: "success",
      });
      saveAsPbtxt(res.data, res.data);
    } else {
      handleClose();
      ElMessage.error(res.msg);
    }
  });
};

// 取消订单cancelOrder
const cancelOrderfun = (item: { id: string }) => {
  // console.log(item.id);
  ElMessageBox.confirm("请确定要取消订单吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    customClass: "custom-message-box",
    type: "Warning",
  })
    .then(() =>
      cancelOrder(item.id).then((res) => {
        if (res.data) {
          loadData(temparam);
          ElMessage({
            message: "取消成功",
            type: "success",
          });
        } else {
          ElMessage.error("取消失败");
        }
      })
    )
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
};
// 支付payItem
const payItem = (item: any) => {
  console.log(item);
  openDialog();
  orderStore.notifyOrderCmbcode(item.id);
};
const dialogVisible1 = ref(false);
const openDialog = () => {
  // console.log(dialogVisible, "!23");
  dialogVisible1.value = true;
};
const updateDialog1 = (value: boolean) => {
  // console.log(dialogVisible, "!23");
  dialogVisible1.value = value;
};
const handleClose1 = () => {
  dialogVisible1.value = false;
  // isOpen.value = false;
};
const qr = ref("");
const qrCanvas = ref<HTMLCanvasElement | null>(null);
const qrCodeUrl = ref<string>("");
watch(
  () => orderStore.$state.qrCode,
  (newVal) => {
    console.log(newVal);
    qr.value = newVal;
    if (qrCanvas.value) {
      // QRCode.toCanvas(qrCanvas.value, qr.value, (error) => {
      //   if (error) console.error(error);
      // });
      QRCode.toDataURL(qr.value)
        .then((url: string) => {
          qrCodeUrl.value = url;
        })
        .catch((error: any) => {
          if (error) console.error(error);
        });
    }
    openDialog();
  }
);
watch(
  () => orderStore.$state.paymentcode,
  (newVal, oldVal) => {
    console.log(newVal, oldVal, "paymentcode");
    if (newVal != "W") {
      if (newVal != "P") {
        loadData(temparam);
        handleClose1();
      }
    }
  }
);
</script>

<style lang="scss">
.demo-form-inline .el-input {
  --el-input-width: 180px;
}

.demo-form-inline .el-select {
  --el-select-width: 180px;
}
.title {
  font-size: 20px;
  font-weight: bold;
  // padding: 10px 0 30px;
  margin-bottom: 20px;
}
.prdstyle {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #efefef;
  padding: 10px 0;
  &:last-child {
    border: 0;
  }
  .left {
    display: flex;
    img {
      width: 80px;
      height: 80px;
      background: #f8f8f8;
      margin-right: 10px;
    }
    .name {
      font-size: 16px;
      font-weight: bold;
    }
    .tag {
      font-size: 12px;
      color: #999;
      margin-top: 25px;
      span {
        color: red;
        font-size: 16px;
        font-weight: bold;
        margin-right: 5px;
      }
    }
  }
}
/* 自定义消息框按钮样式 */
.custom-message-box .el-button {
  padding: 10px 20px;
  background-color: #d01c1b;
  color: white;
  border: none;
}

.custom-message-box .el-button.cancel {
  background-color: #fff;
}
.closeBtn {
  padding: 30px 30px 0 0;
  text-align: right;
}
.title {
  font-size: 16px;
  padding: 15px 0 0;
  text-align: center;
  font-weight: bold;
  color: #000;
}
.imgtag {
  text-align: center;
}
.imgtag img {
  padding: 20px;
  display: block;
  margin: auto;
}
</style>
